package com.piece.module.spider.executor.shape;

import com.piece.module.spider.context.SpiderContext;
import com.piece.module.spider.support.SpiderNode;
import com.piece.module.spider.util.ExpressionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;

/**
 * 定义变量执行器
 */
@Slf4j
@Component
public class VariableExecutor implements ShapeExecutor {

	private static final String VARIABLE_NAME = "variable-name";

	private static final String VARIABLE_VALUE = "variable-value";

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String,Object> variables) {
		List<Map<String, String>> variableList = node.getListJsonValue(VARIABLE_NAME, VARIABLE_VALUE);
		for (Map<String, String> nameValue : variableList) {
			Object value = null;
			String variableName = nameValue.get(VARIABLE_NAME);
			String variableValue = nameValue.get(VARIABLE_VALUE);
			try {
				value = ExpressionUtil.execute(variableValue, variables);
				log.debug("设置变量{}={}", variableName, value);
				context.pause(node.getNodeId(),"common", variableName,value);
			} catch (Exception e) {
				log.error("设置变量{}出错，异常信息：{}", variableName,e);
				ExceptionUtils.wrapAndThrow(e);
			}
			variables.put(variableName, value);
		}
	}

	@Override
	public String supportShape() {
		return "variable";
	}

	@Override
	public boolean isThread() {
		return false;
	}
}
